<template>
  <Modal v-model="visible" width="550" :title="this.id ? '甲方业绩确认证明编辑' : '甲方业绩确认证明新增'"
    @on-visible-change="closeModal">
    <Form ref="form" :model="form" :rules="rules" :label-width="160">
      <FormItem label="业绩确认周期:" prop="period">
        <DatePicker v-model="form.period" @on-change="onChange" type="daterange"
          placeholder="请选择确认周期" style="width: 100%;"></DatePicker>
      </FormItem>
      <FormItem label="甲方是否确认业绩:" prop="flag">
        <Select v-model="form.flag" placeholder="请选择是否确认业绩" @on-change='changeFlag'>
          <Option :value="1">是</Option>
          <Option :value="2">否</Option>
        </Select>
      </FormItem>
      <FormItem label="快递单号:" prop="expressNo">
        <Input v-model="form.expressNo" placeholder="请输入快递单号或其他文本" :maxlength='30'>
        </Input>
      </FormItem>
      <FormItem label="本次业绩总销金额:" prop="salesAmount">
        <Input v-model="form.salesAmount" type="number" placeholder="请输入金额">
        <span slot="append">元</span>
        </Input>
      </FormItem>
      <FormItem label="业绩确认附件类型:" prop="attachType" :key="form.flag">
        <Select v-model="form.attachType" placeholder="请选择业绩确认附件类型" clearable>
          <Option v-for="(itm, idx) in attachTypes" :key="itm.key" :value="itm.key">
            {{itm.value}}</Option>>
        </Select>
      </FormItem>
      <FormItem label="业绩确认图:" prop="appendix">
        <Upload ref="upload" name="multipartFile" multiple :action="upload.reqUrl"
          :headers="upload.headers" :data="upload.data" :show-upload-list="false"
          :max-size="10240" :on-exceeded-size="onExceededSize" :on-success="onSuccess">
          <Button icon="ios-cloud-upload-outline">附件上传</Button>
          <p slot="tip">支持各种格式文件</p>
        </Upload>
        <div class="confirm-images">
          <p v-for="(item, index) in form.appendix" :key="index">
            <span @click="onDownload(item)">{{ item.name }}</span>
            <Icon type="ios-close" size="24" color="#3366ff" @click="onDelete(index)" />
          </p>
        </div>
      </FormItem>
      <FormItem label="备注:">
        <Input v-model="form.remarks" :maxlength="300" show-word-limit :rows="4"
          type="textarea" placeholder="请输入" />
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="onClose">取消</Button>
      <Button type="primary" :loading="loading" @click="onConfirm">确定</Button>
    </div>
  </Modal>
</template>

<script>
  import toolMgr from '@/biz/base/tool.js'
  import proveMgr from '@/biz/caseReport/ownerProve.js'

  export default {
    props: {
      id: [Number, String],
      refresh: Function
    },
    data() {
      let attachTypes = this.$dt.dictInfo().voucherAttachType
      return {
        visible: false,
        form: {
          buildingId: this.$dt.buildInfo().housesId,
          period: [],
          flag: '',
          salesAmount: '',
          expressNo: '',
          appendix: [],
          remarks: '',
          attachType: ''
        },
        rules: {
          period: [
            { required: true, type: 'array', message: '请选择业绩确认周期' },
          ],
          attachType: [
            { required: true, message: '请选择业绩确认附件类型' },
          ],
          flag: [
            { required: true, type: 'number', message: '请选择甲方是否确认业绩', trigger: 'change' },
          ],
          salesAmount: [
            { required: true, message: '请填写本次业绩总销金额', trigger: 'blur' },
          ],
          appendix: [
            { required: true, message: '请上传业绩确认图' },
          ],
        },
        keyFlag: '',
        attachTypes,
        upload: toolMgr.unloadImage(),
        loading: false
      }
    },
    methods: {
      changeFlag(val) {
        this.keyFlag = val
        if (val == 2) {
          this.rules.attachType = [{ required: false, message: '' }]
        } else {
          this.rules.attachType = [{ required: true, message: '请选择业绩确认附件类型' }]
        }
      },
      // 设置利率值
      onConfirm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (!this.form.period || !this.form.period[0] || !this.form.period[1]) {
              this.$Message.error('业绩确认周期不可为空')
              return
            }
            let params = {
              buildingId: this.form.buildingId,
              confirmStart: this.form.period[0] ? this.form.period[0] : null,
              confirmEnd: this.form.period[1] ? this.form.period[1] : null,
              flag: this.form.flag,
              expressNo: this.form.expressNo,
              attachType: this.form.attachType ?? '',
              salesAmount: this.form.salesAmount,
              appendix: JSON.stringify(this.form.appendix),
              remarks: this.form.remarks
            }
            this.loading = true
            if (this.id) this.onUpdate(params)
            else this.onAdd(params)
          }
        })
      },
      onAdd(params) {
        proveMgr.add(params).then(() => {
          this.$Message.success('新增成功')
          this.loading = false
          this.onClose()
          this.refresh()
        }).catch(err => {
          this.loading = false
        })
      },
      onUpdate(params) {
        proveMgr.update({
          ...params,
          proveId: this.form.proveId,
          updateId: this.$dt.userInfo().userId,
          userName: this.$dt.userInfo().userName
        }).then(() => {
          this.$Message.success('修改成功')
          this.loading = false
          this.onClose()
          this.refresh()
        }).catch(err => {
          this.loading = false
        })
      },
      // 上传成功
      onSuccess(res, file, fileList) {
        if (res.code == '200') {
          this.form.appendix.push({
            url: res.data.imageURL,
            name: file.name
          })
        } else {
          this.$Message.error(res.msg)
        }
      },
      // 文件超过大小
      onExceededSize(file) {
        this.$Message.warning('最大支持10M')
      },
      // 点击单个文件名下载
      onDownload(data) {
        let x = new XMLHttpRequest()
        x.open('GET', data.url, true)
        x.responseType = 'blob'
        x.onload = function(e) {
          let href = window.URL.createObjectURL(x.response),
            a = document.createElement('a')
          a.href = href
          a.download = data.name
          a.click()
        }
        x.send()
      },
      // 删除业绩确认图
      onDelete(index) {
        this.form.appendix.splice(index, 1)
      },
      // 周期选择框change
      onChange(val) {
        val = this.$dt.tool.handleDateRange(val)
        this.form.period = val
      },
      onClose() {
        this.visible = false
      },
      closeModal(res) {
        if (res && this.id) {
          proveMgr.info(this.id).then(res => {
            console.log(res)
            this.form = { ...res }
            console.log(this.form, res)
            this.changeFlag(res.flag)
          })
        } else {
          this.form = {
            buildingId: this.$dt.buildInfo().housesId,
            period: [],
            flag: '',
            salesAmount: '',
            appendix: [],
            remarks: ''
          }
          this.$refs.form.resetFields()
        }
      },
    },
  }
</script>

<style lang='scss' scoped>
  .confirm-images {
    display: flex;
    flex-wrap: wrap;

    p {
      margin-right: 12px;
      display: flex;
      align-items: center;
    }

    span {
      color: #3366ff;
      text-decoration: underline;
      cursor: pointer;
    }

    i {
      cursor: pointer;
      margin-top: 2px;
    }
  }
</style>